/********************
File Name: FiveWayKey.c
Author: Jin-Lei Li
Edition: 1.0
Description: The five key switch is used to control the LEDs in the STC32G12K128 board.
Date: 2023-12-10
Email: lijinlei0907@163.com
Ref: https://www.stcaimcu.com/forum.php?mod=viewthread&tid=463
********************/
#include <STC32G.H>

typedef unsigned char u8;
typedef unsigned int u16;
typedef unsigned long int u32;

#define MAIN_Fosc 35000000UL // main frequency

sbit Key_Up = P7^4;
sbit Key_Down = P7^3;
sbit Key_Left = P7^2;
sbit Key_Right = P7^1;
sbit Key_Middle = P7^0;

u8 LED_Code[8] = {0xFE,0xFD,0xFB,0xF7,0xEF,0xDF,0xBF,0x7F};

void delayms(u16 ms);
void KeyScan();

//u8 KeyNumber;

void main()
{
	EAXFR = 1;
	CKCON = 0x00;
	WTST = 0x00;
	
	P1M1 = 0x00;P1M0 = 0x00;
	P2M1 = 0x00;P2M0 = 0x00;
	P3M1 = 0x00;P3M0 = 0x00;
	P4M1 = 0x00;P4M0 = 0x00;
	P5M1 = 0x00;P5M0 = 0x00;
	P6M1 = 0x00;P6M0 = 0x00;
	P7M1 = 0x00;P7M0 = 0x00;
	
	while(1)
	{
		KeyScan();
	}
}

void KeyScan()
{
	static u8 KeyState_Up,KeyState_Down,KeyState_Left,KeyState_Right,KeyState_Middle;
	if(Key_Up == 0 && KeyState_Up == 0)
	{
		delayms(10);
		if(Key_Up == 0 && KeyState_Up == 0)
		{
			KeyState_Up = 1;
			P2 = LED_Code[1];
		}
	}
	if(Key_Up == 1)
	{
		KeyState_Up = 0;
		//P2 = 0xFF;
	}
	//--------------------------------------------
	if(Key_Down == 0 && KeyState_Down == 0)
	{
		delayms(10);
		if(Key_Down == 0 && KeyState_Down == 0)
		{
			KeyState_Down = 1;
			P2 = LED_Code[2];
		}
	}
	if(Key_Down == 1) 
	{
		KeyState_Down = 0;
		//P2 = 0xFF;
	}
	//-------------------------------------------
	if(Key_Left == 0 && KeyState_Left == 0)
	{
		delayms(10);
		if(Key_Left == 0 && KeyState_Left == 0)
		{
			KeyState_Left = 1;
			P2 = LED_Code[3];
		}
	}
	if(Key_Left == 1)
	{
		KeyState_Left = 0;
		//P2 = 0xFF;
	}
	//----------------------------------------
	if(Key_Right == 0 && KeyState_Right == 0)
	{
		delayms(10);
		if(Key_Right == 0 && KeyState_Right == 0)
		{
			KeyState_Right = 1;
			P2 = LED_Code[4];
		}
	}
	if(Key_Right == 1)
	{
		KeyState_Right = 0;
		//P2 = 0xFF;
	}
	//--------------------------------------
	if(Key_Middle == 0 && KeyState_Middle == 0)
	{
		delayms(10);
		if(Key_Middle == 0 && KeyState_Middle == 0)
		{
			KeyState_Middle = 1;
			P2 = LED_Code[5];
		}
	}
	if(Key_Middle == 1)
	{
		KeyState_Middle = 0;
		//P2 = 0xFF;
	}
}

void delayms(u16 ms)
{
	u16 i;
	do
	{
		i = MAIN_Fosc / 6000;
		while(--i);
	}
	while(--ms);
}